<template>
    <div>
        <div class="topBox">
            <div class="title">增值服务</div>
        </div>
        <div class="rechargeBox">
            <div class="title1">背调充值</div>
            <div class="title2" @click="downloadDemo">背调报告示例</div>
        </div>
        <div class="productBox">
            <div class="productItem" v-for="(item, index) in productList" :key="index"
                :class="selectIndex == index ? 'selectProduct' : ''" @click="changeSelect(index, item.id)">
                <div class="itemTop">
                    <div class="itemTitle">
                        {{ userInfo.userinfo.first_order == 1 ? (Number(item.first_price) != 0 ? '首单权益' + '(' +  item.num + '次)' : item.title) :
                        item.title }}
                    </div>
                    <div class="itemLabel" v-if="userInfo.userinfo.first_order == 1 && Number(item.first_price) != 0 && Number(item.first_price) != Number(item.original_price)">
                        <span>{{ ((Number(item.first_price) / Number(item.original_price))*10).toFixed(1) }}折</span>
                    </div>
                    <div class="itemLabel" v-if="userInfo.userinfo.first_order == 1 && Number(item.first_price) == 0 && Number(item.price) != Number(item.original_price)">
                        <span>{{ ((Number(item.price) / Number(item.original_price))*10).toFixed(1) }}折</span>
                    </div>
                    <div class="itemLabel"
                        v-if="userInfo.userinfo.first_order == 0 && Number(item.original_price) != 0 && Number(item.price) != Number(item.original_price)">
                        {{ ((Number(item.price) / Number(item.original_price))*10).toFixed(1) }}折
                    </div>
                </div>
                <div class="itemBot">
                    <div class="itemPrice">
                        {{ userInfo.userinfo.first_order == 1 ? (Number(item.first_price) != 0 ? item.first_price : item.price) :
                        item.price }}<span
                            style="font-size: 16px;">元</span>
                    </div>
                    <div class="itemPriceOld" v-if="Number(item.original_price) != 0 && userInfo.userinfo.first_order == 1 && Number(item.first_price) != 0 && Number(item.first_price) != Number(item.original_price)">
                        {{ item.original_price }}
                        <span style="font-size: 16px;">元</span>
                    </div>
                    <div class="itemPriceOld" v-if="Number(item.original_price) != 0 && userInfo.userinfo.first_order == 1 && Number(item.first_price) == 0 && Number(item.price) != Number(item.original_price)">
                        {{ item.original_price }}
                        <span style="font-size: 16px;">元</span>
                    </div>
                    <div class="itemPriceOld" v-if="Number(item.original_price) != 0 && userInfo.userinfo.first_order == 0 && Number(item.price) != Number(item.original_price)">
                        {{ item.original_price }}
                        <span style="font-size: 16px;">元</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="btnBox">
            <div class="buyBtn" @click="goSelPay">
                立即购买
            </div>
        </div>
        <div class="tipBox" v-html="tips">

        </div>
        <el-dialog v-model="open" :close-on-click-modal="false" width="600px" title="选择购买方式" :z-index="9">
            <div class="payBox">
                <div class="payItem" v-for="(item, index) in payArr" :key="index" @click="payIndex = index"
                    :class="payIndex == index ? 'selectPay' : ''">
                    <div style="flex: 1;">
                        <img src="../../../assets/image/zxl/wx_icon.png" v-if="item.value == 1" class="payIcon"></img>
                        <img src="../../../assets/image/zxl/zfb_icon.png" v-if="item.value == 2" class="payIcon">
                    </div>
                    <span>{{ item.label }}</span>
                </div>
                <div class="buyBtn" @click="confirmBuy">
                    立即购买
                </div>
            </div>
        </el-dialog>
        <el-dialog v-model="open1" :close-on-click-modal="false" width="500px" title="付款二维码" :z-index="9"
            @close="endTime">
            <div class="showBox">
                <div class="headTip">
                    <span class="texts">打开手机，使用{{ payIndex == 0 ? '微信' : '支付宝' }}扫码支付，支付倒计时：</span>
                    <el-countdown :value="valueTime" value-style="texts" @finish="endTime" />
                </div>
                <el-image style="width: 200px; height: 200px" :src="buyInfo.code_url"
                    :preview-src-list="[buyInfo.code_url]" fit="fill" />
                <span style="margin-top: 24px;">支付金额：{{ buyInfo.amount }}元</span>
                <div v-if="isChecking" class="loading">
                    <span class="spinner"></span>
                    <p>等待支付确认中...</p>
                </div>
                <div v-if="paymentSuccess" class="success-message">
                    <i class="icon-success"></i>
                    <h3>支付成功！</h3>
                    <p>感谢您的购买，即将跳转到购买页面...</p>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import type { ElMessage, ElMessageBox } from 'element-plus'
import { getProductList, getBdTips, rechargeBackTuning, checkOrder } from '@/api/xl'
import { UserBaseInfo } from '@/api/user'

onMounted(() => {
    getList()
    getInfo()
    getTip()
})

const productList = ref([])
const payArr = ref([{
    label: '微信支付',
    value: 1
}, {
    label: '支付宝支付',
    value: 2
}])
const tips = ref('')
const selectIndex = ref(-1)
const payIndex = ref(0)
const selectId = ref(0)
const form = ref({})
const buyInfo = ref({})
const userInfo = ref({})
const open = ref(false)
const open1 = ref(false)
const valueTime = ref(Date.now() + 1000 * 60 * 60 * 0.5)
const isChecking = ref(false);
const paymentSuccess = ref(false);
let checkTimer = null;


const getList = async () => {
    await getProductList().then(res => {
        productList.value = res.data
    })
}

const getInfo = async () => {
    await UserBaseInfo({}).then((res) => {
        userInfo.value = res.data
    })
}

const getTip = async () => {
    await getBdTips().then(res => {
        tips.value = res.data.bd_tips
    })
}

const changeSelect = (index, id) => {
    selectIndex.value = index;
    selectId.value = id;
}

const goSelPay = () => {
    if (selectIndex.value == -1) {
        ElMessage({
            message: '请先选择商品！',
            grouping: true,
            type: "error",
        });
    } else {
        open.value = true
        form.value.id = selectId.value
        form.value.num = 1
    }
}

const confirmBuy = async () => {
    if (payIndex.value == 0) {
        form.value.type = 1
    } else {
        form.value.type = 2
    }
    await rechargeBackTuning(form.value).then(res => {
        open1.value = true
        open.value = false
        valueTime.value = Date.now() + 1000 * 60 * 60 * 0.5;
        buyInfo.value = res.data
        startCheckingPayment();
    })
}

// 开始检查支付状态
const startCheckingPayment = () => {
    isChecking.value = true;
    // 立即检查一次
    checkPayment();

    // 然后每隔3秒检查一次，避免过于频繁
    checkTimer = setInterval(checkPayment, 3000);
};

// 检查支付状态
const checkPayment = async () => {
    await checkOrder(buyInfo.value.out_trade_no).then(res => {
        if (res.status == 1) {
            handlePaymentSuccess()
        }
        if (res.status == 0) {
            console.log('订单未支付')
        }
    })
};

// 处理支付成功
const handlePaymentSuccess = () => {
    isChecking.value = false;
    paymentSuccess.value = true;
    clearInterval(checkTimer);

    // 3秒后跳转到订单详情页
    setTimeout(() => {
        open1.value = false
        paymentSuccess.value = false;
        getList()
        // 这里可以使用vue-router进行跳转
        // router.push(`/order/detail/${orderId.value}`);
    }, 2000);
};


const endTime = () => {
    clearInterval(checkTimer);
    open1.value = false
    paymentSuccess.value = false;
    getList()
}


const downloadDemo = () => {
    const urls = 'https://demo-user.niuyuwang.com/static/demo.pdf' // 替换为实际文件 URL
    const newWindow = window.open(urls, '_blank');

    // 检查是否成功打开新窗口（可能被浏览器弹窗阻止）
    if (!newWindow) {
        alert('浏览器阻止了弹出窗口，请允许弹出窗口后重试');
    }
    // const a = document.createElement('a');
    // a.href = urls;
    // a.target = '_blank';
    // a.download = '背调报告示例.pdf'; // 自定义下载文件名
    // a.rel = 'noopener noreferrer';
    // a.setAttribute('crossorigin', 'anonymous')
    // // a.setAttribute('Content-Disposition', 'attachment; filename="filename.pdf"')
    // document.body.appendChild(a);
    // a.click();
    // document.body.removeChild(a);
}
</script>

<style lang="scss" scoped>
.topBox {
    padding: 9px 0 24px 0;
    border-bottom: solid 1px #e8e8e8;
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: bolder;
    color: #333;
}

.rechargeBox {
    padding: 18px 0;
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: bolder;

    .title1 {
        margin-right: 14px;
        color: #333;
    }

    .title2 {
        color: #01509f;
        cursor: pointer;
    }
}

.productBox {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 39px;

    .selectProduct {
        border: 1px solid #01509f !important;
    }

    .productItem {
        width: 262px;
        height: 160px;
        padding: 0 25px;
        box-sizing: border-box;
        border-radius: 4px;
        border: 1px solid #eaeaea;
        margin-right: 16px;
        margin-bottom: 16px;
        display: flex;
        flex-direction: column;
        // align-items: flex-start;

        .itemTop {
            height: 24px;
            display: flex;
            align-items: flex-end;
            margin-top: 36px;
            margin-bottom: 40px;

            .itemTitle {
                color: #333;
                font-size: 16px;
                margin-right: 7px;
            }

            .itemLabel {
                font-size: 14px;
                color: #fff;
                background-color: #e14d5d;
                border-radius: 4px;
                padding: 5px 8px;
            }
        }

        .itemBot {
            display: flex;
            align-items: flex-end;

            .itemPrice {
                font-size: 20px;
                color: #333;
                margin-right: 4px;
            }

            .itemPriceOld {
                color: #999;
                text-decoration: line-through;
                font-size: 16px;
            }
        }
    }
}

.btnBox {
    width: 100%;
    height: 36px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;

    .buyBtn {
        width: 108px;
        height: 36px;
        border-radius: 6px;
        box-sizing: border-box;
        text-align: center;
        line-height: 36px;
        color: #fff;
        background-color: #01509f;
        font-size: 16px;
    }
}

.tipBox {
    background-color: #f3f8fb;
    border-radius: 4px;
    padding: 18px 15px;
    box-sizing: border-box;
    margin-top: 28px;
}

.payBox {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 320px;

    .selectPay {
        border: 1px solid #01509f !important;
    }

    .payItem {
        width: 400px;
        padding: 25px;
        box-sizing: border-box;
        border-radius: 6px;
        border: 1px solid #eaeaea;
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: bolder;
        color: #333;

        .payIcon {
            width: 48px;
            height: 48px;
            flex-shrink: 0;
        }
    }

    .buyBtn {
        width: 146px;
        height: 36px;
        border-radius: 6px;
        box-sizing: border-box;
        text-align: center;
        line-height: 36px;
        color: #fff;
        background-color: #01509f;
        font-size: 16px;
        margin-top: 24px;
    }
}

.showBox {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .headTip {
        display: flex;
        align-items: center;
        color: #333;
        font-size: 16px;
        font-weight: normal;
        margin-bottom: 24px;

        ::v-deep .el-statistic__content {
            font-size: 16px;
        }

        ::v-deep .el-statistic__number {
            color: #333;
            font-size: 16px;
            font-weight: normal;
        }
    }
}

.payment-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 2rem;
}

.qr-code-wrapper {
    text-align: center;
}

.qr-code {
    width: 240px;
    height: 240px;
    padding: 10px;
    border: 1px solid #eee;
    border-radius: 8px;
    margin-bottom: 1rem;
}

.payment-info {
    color: #666;
    margin-bottom: 1.5rem;
}

.loading {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #666;
    margin-top: 12px;
}

.spinner {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 3px solid rgba(0, 0, 0, 0.1);
    border-radius: 50%;
    border-top-color: #42b983;
    animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

.success-message,
.error-message {
    text-align: center;
    padding: 2rem;
    border-radius: 8px;
    width: 100%;
    max-width: 400px;
    margin-top: 12px;
}

.success-message {
    background-color: #f0f9f0;
    border: 1px solid #c3e6c3;
}

.error-message {
    background-color: #fff5f5;
    border: 1px solid #ffe3e3;
}

.icon-success,
.icon-error {
    font-size: 48px;
    margin-bottom: 1rem;
}

.icon-success {
    color: #42b983;
}

.icon-error {
    color: #ff4d4f;
}

.retry-btn {
    margin-top: 1rem;
    padding: 0.5rem 1rem;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.retry-btn:hover {
    background-color: #359e75;
}
</style>